<template>
    <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
            <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
            <el-input v-model="form.role" value="健康管家" disabled />
        </el-form-item>
        <el-form-item>
            <el-button @click="onReset">重置</el-button>
            <el-button type="primary" @click="onSubmit">保存</el-button>
            <el-button type="warning" @click="onRP">重置密码</el-button>
        </el-form-item>
    </el-form>
</template>
<script setup>
import { inject, ref, reactive, watch, defineProps, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'
import qs from 'qs'
const props = defineProps({ user: Object })
const emit = defineEmits(['success'])

const axios = inject('axios')
const formRef = ref()
const form = reactive({
    userId: '',
    username: '',
    phone: '',
    role: ''
})

const rules = {
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
    role: [{ required: true, message: '请选择角色', trigger: 'change' }]
}

// watch props.user，初始化编辑数据
watch(() => props.user, (val) => {
    if (val) Object.assign(form, val)
}, { immediate: true })
const onReset = () => {
    if (props.user) Object.assign(form, props.user)
    formRef.value && formRef.value.clearValidate()
}
const onSubmit = () => {
    formRef.value.validate(async valid => {
        if (!valid) return
        await axios.post('/user/update', qs.stringify(form))
        ElMessage.success('修改成功')
        emit('success')
    })
}
const onRP = () => {
    formRef.value.validate(async valid => {
        if (!valid) return
        form.password = form.phone.slice(-6)
        await axios.post('/user/update', qs.stringify(form))
        ElMessage.success('密码修改成功')
        emit('success')
    })
}
</script>
  